#include <iostream>
#include <memory>

#include "TcpServer.h"

#include "TcpConnection.h"
#include "Acceptor.h"
#include "EventLoop.h"
#include "MyTask.h"
#include "ThreadPool.h"
#include "EchoServer.h"



void onNewConnection(const TcpConnectionPtr& conn)
{
    std::cout<<"new connection "<<conn->toString()<<std::endl;
}

void onNewMessage(const TcpConnectionPtr& conn)
{
    //reactor/EventLoop开始读取数据，然后将数据放入线程池进行处理
    
    std::string msg = conn->receive();
    std::cout<<">>receive message = "<<msg<<std::endl;
    std::shared_ptr<ThreadPool> threadpool = ThreadPool::getInstance();
    auto task = std::make_shared<MyTask>(conn,msg);
    threadpool->addTask(task);
    /**
     * 在此处需要将接收到的数据msg打包给线程池进行处理
     */
    /*
    MyTask task(conn,msg);
    threadpool.addTask(std::bind(&MyTask::process,&task));
    */
}

void onClose(const TcpConnectionPtr& conn)
{
    std::cout<<"close connection"<<std::endl;
}

void test(){
    Acceptor acceptor("127.0.0.1",8888);
    acceptor.ready();

    EventLoop loop(acceptor);
    loop.setNewConnectionCallback(std::move(onNewConnection));
    loop.setMessageCallback(std::move(onNewMessage));
    loop.setCloseCallback(std::move(onClose));

    loop.loop();
}

void test2()
{   
    auto threadPool = ThreadPool::getInstance();
    threadPool->start();
    //构建一个线程，然后这个线程向线程池里面添加任务
    TcpServer server("127.0.0.1",8888);
    server.setAllCallback(onNewConnection,onNewMessage,onClose);
    server.start();


}

void test3(){
    EchoServer server("127.0.0.1",8888);
    server.start();
}

int main(){
    test3();
    return 0;
}